package com.ecommerce.dao;

import com.ecommerce.model.Coupon;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class CouponDAO {

    public boolean createCoupon(Coupon coupon) {
        String sql = "INSERT INTO coupons (code, description, discount_amount, min_order_amount, " +
                "start_date, end_date, usage_limit, used_count, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, coupon.getCode());
            stmt.setString(2, coupon.getDescription());
            stmt.setDouble(3, coupon.getDiscountAmount());
            stmt.setDouble(4, coupon.getMinOrderAmount());
            stmt.setDate(5, new java.sql.Date(coupon.getStartDate().getTime()));
            stmt.setDate(6, new java.sql.Date(coupon.getEndDate().getTime()));
            stmt.setInt(7, coupon.getUsageLimit());
            stmt.setInt(8, coupon.getUsedCount());
            stmt.setString(9, coupon.getStatus());

            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;

        } catch (SQLException e) {
            System.out.println("创建优惠券失败: " + e.getMessage());
            return false;
        }
    }

    public List<Coupon> getAllCoupons() {
        List<Coupon> coupons = new ArrayList<>();
        String sql = "SELECT * FROM coupons ORDER BY id DESC";

        try (Connection conn = DatabaseConnection.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            while (rs.next()) {
                coupons.add(extractCouponFromResultSet(rs));
            }

        } catch (SQLException e) {
            System.out.println("获取优惠券列表失败: " + e.getMessage());
        }

        return coupons;
    }

    public Coupon getCouponByCode(String code) {
        String sql = "SELECT * FROM coupons WHERE code = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, code);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return extractCouponFromResultSet(rs);
            }

        } catch (SQLException e) {
            System.out.println("获取优惠券失败: " + e.getMessage());
        }

        return null;
    }

    public Coupon getCouponById(int id) {
        String sql = "SELECT * FROM coupons WHERE id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, id);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return extractCouponFromResultSet(rs);
            }

        } catch (SQLException e) {
            System.out.println("获取优惠券失败: " + e.getMessage());
        }

        return null;
    }

    public boolean updateCoupon(Coupon coupon) {
        String sql = "UPDATE coupons SET code = ?, description = ?, discount_amount = ?, " +
                "min_order_amount = ?, start_date = ?, end_date = ?, usage_limit = ?, " +
                "used_count = ?, status = ? WHERE id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setString(1, coupon.getCode());
            stmt.setString(2, coupon.getDescription());
            stmt.setDouble(3, coupon.getDiscountAmount());
            stmt.setDouble(4, coupon.getMinOrderAmount());
            stmt.setDate(5, new java.sql.Date(coupon.getStartDate().getTime()));
            stmt.setDate(6, new java.sql.Date(coupon.getEndDate().getTime()));
            stmt.setInt(7, coupon.getUsageLimit());
            stmt.setInt(8, coupon.getUsedCount());
            stmt.setString(9, coupon.getStatus());
            stmt.setInt(10, coupon.getId());

            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;

        } catch (SQLException e) {
            System.out.println("更新优惠券失败: " + e.getMessage());
            return false;
        }
    }

    public boolean useCoupon(int couponId) {
        String sql = "UPDATE coupons SET used_count = used_count + 1 WHERE id = ? AND used_count < usage_limit";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, couponId);
            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;

        } catch (SQLException e) {
            System.out.println("使用优惠券失败: " + e.getMessage());
            return false;
        }
    }

    public boolean toggleCouponStatus(int couponId) {
        String sql = "UPDATE coupons SET status = IF(status = 'active', 'inactive', 'active') WHERE id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, couponId);
            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;

        } catch (SQLException e) {
            System.out.println("更新优惠券状态失败: " + e.getMessage());
            return false;
        }
    }

    public boolean deleteCoupon(int couponId) {
        String sql = "DELETE FROM coupons WHERE id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, couponId);
            int rowsAffected = stmt.executeUpdate();
            return rowsAffected > 0;

        } catch (SQLException e) {
            System.out.println("删除优惠券失败: " + e.getMessage());
            return false;
        }
    }

    private Coupon extractCouponFromResultSet(ResultSet rs) throws SQLException {
        Coupon coupon = new Coupon();
        coupon.setId(rs.getInt("id"));
        coupon.setCode(rs.getString("code"));
        coupon.setDescription(rs.getString("description"));
        coupon.setDiscountAmount(rs.getDouble("discount_amount"));
        coupon.setMinOrderAmount(rs.getDouble("min_order_amount"));
        coupon.setStartDate(rs.getDate("start_date"));
        coupon.setEndDate(rs.getDate("end_date"));
        coupon.setUsageLimit(rs.getInt("usage_limit"));
        coupon.setUsedCount(rs.getInt("used_count"));
        coupon.setStatus(rs.getString("status"));
        return coupon;
    }
}